/**
 * AI创作工坊页面
 * 集成问答系统、观点建议、提纲生成等功能
 */
import React, { useState, useEffect } from 'react';
import { Progress, Card, Button, message, Space } from 'antd';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { StartupModal } from '@/components/brainstorm/StartupModal';
import { QuestionPanel } from '@/components/brainstorm/QuestionPanel';
import { QuestionSummary } from '@/components/brainstorm/QuestionSummary';
import { ViewpointPanel } from '@/components/brainstorm/ViewpointPanel';
import { OutlinePanel } from '@/components/brainstorm/OutlinePanel';
import { ParagraphGenerationPanel } from '@/components/brainstorm/ParagraphGenerationPanel';
import { useBrainstormStore } from '@/stores/brainstorm.store';
import './style.css';

type WorkshopStage = 'startup' | 'questions' | 'summary' | 'viewpoints' | 'outline' | 'writing';

const BrainstormWorkshop: React.FC = () => {
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const { currentSession, loadSession } = useBrainstormStore();

  const [stage, setStage] = useState<WorkshopStage>('startup');
  const [showStartup, setShowStartup] = useState(false);

  // 智能恢复会话状态
  useEffect(() => {
    if (!currentSession) {
      // 没有会话，显示启动状态
      setStage('startup');
      setShowStartup(false);
      return;
    }

    // 根据会话进度自动恢复到最后阶段
    const { questions, viewpoints, outline, stage: sessionStage } = currentSession;

    // 检查是否有已回答的问题
    const hasAnsweredQuestions = questions.some(q => q.answer && !q.skipped);
    const allQuestionsAnswered = questions.length > 0 &&
      questions.every(q => (q.answer && !q.skipped) || q.skipped);

    if (outline) {
      // 如果有提纲，跳到提纲阶段
      setStage('outline');
    } else if (viewpoints && viewpoints.length > 0) {
      // 如果有观点，跳到观点阶段
      setStage('viewpoints');
    } else if (allQuestionsAnswered && questions.length > 0) {
      // 如果所有问题都已回答，跳到汇总阶段
      setStage('summary');
    } else if (hasAnsweredQuestions) {
      // 如果有部分问题已回答，继续问答阶段
      setStage('questions');
    } else if (questions.length > 0) {
      // 如果有问题但没回答，进入问答阶段
      setStage('questions');
    } else {
      // 有会话但没有任何内容，回到启动状态
      setStage('startup');
    }

    setShowStartup(false);
  }, [currentSession]);

  // 从URL参数获取热点信息
  const hotTopicId = searchParams.get('hotTopicId');
  const hotTopicTitle = searchParams.get('hotTopicTitle');

  // 计算进度百分比
  const getProgress = () => {
    switch (stage) {
      case 'startup':
      case 'questions':
        return 0;
      case 'summary':
        return 33;
      case 'viewpoints':
        return 50;
      case 'outline':
        return 66;
      case 'writing':
        return 100;
      default:
        return 0;
    }
  };

  // 获取阶段名称
  const getStageName = () => {
    switch (stage) {
      case 'startup':
      case 'questions':
      case 'summary':
        return '头脑风暴';
      case 'viewpoints':
      case 'outline':
        return '内容撰写';
      case 'writing':
        return '优化完成';
      default:
        return '头脑风暴';
    }
  };

  // 启动会话
  const handleStart = (sessionId: string) => {
    setShowStartup(false);
    setStage('questions');
  };

  // 完成问答
  const handleQuestionComplete = () => {
    setStage('summary');
  };

  // 继续到观点阶段
  const handleContinueToViewpoints = () => {
    message.success('问答完成！即将生成观点建议...');
    setStage('viewpoints');
  };

  // 从观点阶段继续到提纲
  const handleContinueToOutline = () => {
    message.success('观点已选择！即将生成提纲...');
    setStage('outline');
  };

  // 从提纲继续到写作
  const handleContinueToWriting = () => {
    message.success('提纲已完成！即将开始写作...');
    setStage('writing');
    // TODO: Story 7.1.5 实现写作阶段
  };

  // 保存草稿
  const handleSaveDraft = () => {
    message.success('草稿已保存');
    navigate('/dashboard');
  };

  // 重新开始
  const handleRestart = () => {
    setStage('startup');
    setShowStartup(true);
  };

  return (
    <div className="brainstorm-workshop">
      {/* 页面头部 */}
      <div className="workshop-header">
        <div className="header-content">
          <div>
            <h1>AI创作工坊</h1>
            <div className="session-info">
              {currentSession && (
                <span className="session-title">{currentSession.title}</span>
              )}
            </div>
          </div>
          <Space>
            {currentSession && stage !== 'startup' && (
              <Button onClick={handleSaveDraft}>保存草稿</Button>
            )}
            <Button type="primary" onClick={() => setShowStartup(true)}>
              {currentSession ? '新建会话' : '开始创作'}
            </Button>
          </Space>
        </div>
        <div className="progress-section">
          <Progress
            percent={getProgress()}
            steps={3}
            strokeColor="#52c41a"
            format={() => getStageName()}
          />
        </div>
      </div>

      {/* 主内容区域 */}
      <div className="workshop-content">
        <div className="main-area">
          {stage === 'questions' && (
            <QuestionPanel onComplete={handleQuestionComplete} />
          )}

          {stage === 'summary' && (
            <QuestionSummary
              onContinue={handleContinueToViewpoints}
              onSaveDraft={handleSaveDraft}
              onRestart={handleRestart}
            />
          )}

          {stage === 'viewpoints' && (
            <ViewpointPanel onContinue={handleContinueToOutline} />
          )}

          {stage === 'outline' && (
            <OutlinePanel onContinue={handleContinueToWriting} />
          )}

          {stage === 'writing' && (
            <ParagraphGenerationPanel />
          )}

          {stage === 'startup' && (
            <Card className="empty-state">
              <div className="empty-content">
                <h2>开启你的创作之旅</h2>
                <p>点击"开始创作"按钮，开启AI辅助创作工坊</p>
                <Button
                  type="primary"
                  size="large"
                  onClick={() => setShowStartup(true)}
                >
                  开始创作
                </Button>
              </div>
            </Card>
          )}
        </div>
      </div>

      {/* 启动模式对话框 */}
      <StartupModal
        open={showStartup}
        onClose={() => setShowStartup(false)}
        onStart={handleStart}
        defaultMode={hotTopicId ? 'hot' : 'blank'}
        hotTopicId={hotTopicId || undefined}
        hotTopicTitle={hotTopicTitle || undefined}
      />
    </div>
  );
};

export default BrainstormWorkshop;
